<template>
  <el-container>
    <el-header>
      <div class="head">
        <div class="head-left">
          <div class="userIcon">
            <el-icon style="width: 25px; height: 25px; " color="#67C23A"><UserFilled /></el-icon>
          </div>
          用户类别选择:
        </div>
        <div class="head-center">
          <el-radio-group v-model="role" @change="loadUsersByRole">
            <el-radio label="student">学生</el-radio>
            <el-radio label="teacher">教师</el-radio>
            <el-radio label="admin">管理员</el-radio>
          </el-radio-group>
        </div>
        <div class="head-right">
          <el-button
              type="primary"
              @click="registerForm = {}; addUserDialog = true">添加用户
          </el-button>
        </div>
      </div>
    </el-header>
    <el-main>
      <el-table
          :data="users"
          stripe
          height="500"
          style="width: 95%; margin-left: 50px"
          ref="table"
          @selection-change="handleSelectionChange"
          border
      >
        <el-table-column prop="id" label="用户ID" width="180"/>
        <el-table-column prop="userNumber" label="学工号" width="180"/>
        <el-table-column prop="username" label="用户名" width="180"/>
        <el-table-column prop="phone" label="电话" width="180"/>
        <el-table-column prop="email" label="邮箱" width="180"/>
        <el-table-column prop="address" label="地址"/>
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button
                type="text"
                size="small"
                @click.prevent="modifyUser(users[scope.$index])">
              编辑
            </el-button>
<!--            <el-button-->
<!--                type="text"-->
<!--                size="small"-->
<!--                @click.prevent="deleteUser(users[scope.$index])"-->
<!--                v-show="users[scope.$index].id !== 1">-->
<!--              删除-->
<!--            </el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="paginations.page_index"
                     :page-sizes="paginations.page_sizes"
                     :page-size="paginations.page_size"
                     :layout="paginations.layout"
                     :total="paginations.total">
      </el-pagination>
    </el-main>
  </el-container>
  <el-dialog v-model="addUserDialog" class="dialog" width="35%" title="添加新用户">
    <div class="form">
      <div class="form-body">
      <el-form
          :model="registerForm"
          :rules="rules"
          ref="registerForm"
      >
        <el-form-item label="用户类型" prop="nickname">
          <el-select v-model="registerForm.nickname" placeholder="选择用户类型">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="username">
          <el-input
              v-model="registerForm.username"
              type="text"
              autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="学工号" prop="userNumber">
          <el-input
              v-model="registerForm.userNumber"
              type="text"
              autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="registerForm.password"
              type="password"
              autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="re_password">
          <el-input
              v-model="registerForm.re_password"
              type="password"
              autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
              v-model="registerForm.email"
              type="text"
              autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input
              v-model="registerForm.phone"
              type="text"
              autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input
              v-model="registerForm.address"
              type="text"
              autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="register">添加</el-button>
          <el-button @click="addUserDialog = false">返回</el-button>
        </el-form-item>
      </el-form>
      </div>
    </div>
  </el-dialog>
  <el-dialog v-model="modifyUserDialog">
    <el-form class="register_form" label-width="80px" ref="registerForm" :model="registerForm" :rules="rules">
      <h3>修改用户信息</h3>
      <el-form-item label="id">
        <el-input
            disabled
            v-model="registerForm.id"
            type="text"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input
            v-model="registerForm.username"
            type="text"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input
            v-model="registerForm.password"
            type="password"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="re_password">
        <el-input
            v-model="registerForm.re_password"
            type="password"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
            v-model="registerForm.email"
            type="text"
            autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input
            v-model="registerForm.phone"
            type="text"
            autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input
            v-model="registerForm.address"
            type="text"
            autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label-width="0xp">
        <el-button type="primary" @click="updateUser">更新</el-button>
        <el-button @click="modifyUserDialog = false">返回</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <el-dialog v-model="deleteDialogVisible" title="警告" width="30%" center>
    <span>
      是否确定删除用户: {{ pendingDelete.map(p => p.username).toString() }}？
    </span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDelete"
        >确定</el-button
        >
      </span>
    </template>
  </el-dialog>

</template>

<script>
import {ElMessage} from 'element-plus'
import {ref} from "vue";
import {ifUserNumber, SelectAllUserByNickname} from "../../api/user";
import {UserFilled} from "@element-plus/icons-vue";
export default {
  name: "RolesInformation",
  components: {UserFilled},
  data() {
    return {
      users: [],
      multipleSelection: [],
      addUserDialog: ref(false),
      registerForm: {
        userNumber:"默认",
        username: "默认",
        password: "默认",
        re_password: "默认",
        email: "默认",
        address: "默认",
        phone: "默认号码",
        nickname: "",
      },
      role:'student',
      pendingDelete: [],
      deleteDialogVisible: ref(false),
      modifyUserDialog: ref(false),
      roles: [],
      hasRoles: [],
      page: 1,
      size: 10,
      total: 0,
      //新添用户类型选择
      options: [
        {
          value: 'student',
          label: '学生',
        },
        {
          value: 'teacher',
          label: '教师',
        },
        {
          value: 'admin',
          label: '管理员',
        },
      ],
      paginations: {
        page_index: 1, //当前页面
        total: 0,      //总页数
        page_size: 5,  //每页显示的记录条数
        page_sizes: [5, 10, 15, 20],  //可选择的page_size范围
        layout: "total, sizes, prev, pager, next, jumper"  //翻页属性
      },
      color:'',
      allTableData: [],
      rules: {
        //校验数据
        nickname:[
          { required: true, message: "请选择用户类型", trigger: "blur" },
        ],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        userNumber: [
          { required: true, message: "请输入学工号", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10个数字", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
        ],
        re_password: [
          { required: true, message: "请输入确认密码", trigger: "blur" },
        ],
        email: [{
          type: 'email',
          message: '请输入正确的邮箱地址',
          trigger: ['blur', 'change']
        },{ required: true, message: "请输入邮箱", trigger: "blur" },
        ],
        // 验证手机号
        phone: [{
          pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          message: "请输入正确的手机号码",
          trigger: "blur"
        },
          { required: true, message: "请输入手机号", trigger: "blur" },
        ],
      }
    }
  },
  mounted() {
    this.loadUsersByRole()
  },
  methods: {
    deleteUser(user) {
      this.registerForm = user
      this.deleteDialogVisible = ref(true)
    },
    modifyUser(user) {
      this.registerForm = user
      this.modifyUserDialog = ref(true)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    bathDelete() {
      this.pendingDelete = this.multipleSelection
      this.deleteDialogVisible = ref(true)
    },
    selectable(row) {
      return row.id !== 1
    },
    //添加用户
    register() {
      this.$refs['registerForm'].validate((valid) => {
        if (valid)
        {
          if (this.registerForm.password !== this.registerForm.re_password) {
            this.open3()
            return
          }
          ifUserNumber({userNumber: this.registerForm.userNumber, password: this.registerForm.password}).then(res=>{
            if (res.message === '用户存在')
            {
              ElMessage.error('学工号已存在')
              return
            }else
            {
              this.$axios.post('/user/Register', {
                userNumber: this.registerForm.userNumber,
                username: this.registerForm.username,
                password: this.registerForm.password,
                phone: this.registerForm.phone,
                email: this.registerForm.email,
                address: this.registerForm.address,
                nickname: this.registerForm.nickname,
                userAvatar: 'http://ww4.sinaimg.cn/bmiddle/006DLFVFgy1ft0j2pddjuj30v90uvagf.jpg'
              }).then(success => {
                if (success.data.code === 200) {
                  ElMessage({
                    message: '添加成功',
                    type: 'success'
                  })

                  this.addUserDialog = ref(false),
                      this.loadUsersByRole()
                } else {
                  ElMessage({
                    message: success.data.message,
                    type: 'error'
                  })
                }
              }).catch(fail => {
                console.log(fail)
              })
            }
          })
        } else{
          return false;
        }
      })
    },
    confirmDelete() {
      this.deleteDialogVisible = ref(false)
      let _this = this
      this.$axios.delete("deleteUser", {params:{id:this.registerForm.id}})
          .then(success => {
            if (success.data.code === 200) {
              ElMessage({
                message: '删除成功',
                type: 'success'
              })
              _this.loadUsers()
            } else {
              ElMessage({
                message: success.data.message,
                type: 'error'
              })
            }
          }).catch(fail => {
        console.log(fail)
      })
      this.loadUsersByRole()
    },
    open3 (){
      ElMessage({
        message: '两次密码输入不一致',
        type: 'warning',
      })
    },
    updateUser() {
      this.$refs['registerForm'].validate((valid) => {
            if (valid){
              if (this.registerForm.password !== this.registerForm.re_password) {
                this.open3()
                return
              }else{
                let _this = this
                this.$axios.post("updateUser", {
                  id:this.registerForm.id,
                  username: this.registerForm.username,
                  password: this.registerForm.password,
                  phone: this.registerForm.phone,
                  email: this.registerForm.email,
                  address: this.registerForm.address,
                })
                    .then(success => {
                      if (success.data.code === 200) {
                        this.$notify({
                          title: '成功',
                          message: "用户信息更新成功",
                          type: 'success'
                        });
                        _this.modifyUserDialog = ref(false)
                      } else {
                        ElMessage({
                          message: success.data.message,
                          type: 'error'
                        })
                      }
                    }).catch(fail => {
                  console.log(fail)
                })
              }
            }else{
              return
            }
      })
    },
    //根据当前选择类型加载数据
    loadUsersByRole() {
      SelectAllUserByNickname(this.role).then(response =>{
        this.allTableData = response.data;
        this.setPaginations();
      })
    },

    //分页
    handleSizeChange(page_size) {
      this.paginations.page_index = 1;
      this.paginations.page_size = page_size;
      this.users = this.allTableData.filter((item, index) => {
        return index < page_size;
      });
    },
    handleCurrentChange(page) {
      this.paginations.page_index =page;
      let index = this.paginations.page_size * (page - 1);
      let nums = this.paginations.page_size * page;
      let tables = [];   // 存储跳转页面要显示的记录
      for (let i = index; i < nums; i++) {
        if (this.allTableData[i]) {
          tables.push(this.allTableData[i]);
        }
        this.users = tables;
      }
    },
    setPaginations(){
      this.paginations.total = this.allTableData.length;
      this.paginations.page_index = 1;
      this.paginations.page_size = 5;
      //设置默认的分页数据
      this.users = this.allTableData.filter((item, index) => {
        return index < this.paginations.page_size;
      });
    },
  }
}
</script>

<style scoped>
.head {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.head-left {
  display: flex;
  margin-right: 50px;
  justify-content: center;
  align-items: center;
}
.userIcon {
  display: flex;
  margin-top: 10px;
  margin-right: 10px;
}
.head-center {
  margin-right: 80px;
}
.form {
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.form-head {
  margin-bottom: 20px;
  font-size: 25px;
}
.form-body{
  display: flex;
  justify-content: center;
}
</style>
